package com.fengba.nanzhi.tabbar02;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fengba.nanzhi.fengba.R;
import com.fengba.nanzhi.login.Login;
import com.fengba.nanzhi.myfengba.MyCF;
import com.fengba.nanzhi.notice.Notice;
import com.fengba.nanzhi.tabbar04.wz.AddressActivity;
import com.fengba.nanzhi.tabbar04.wz.IdnumberActivity;
import com.fengba.nanzhi.tabbar04.wz.ParentUserActivity;
import com.fengba.nanzhi.tabbar04.wz.WebViewActivity;
import com.fengba.nanzhi.utils.OKManager;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;


/**
 * Created by duan on 2018/4/1.
 */

public class Tabbar02 extends Fragment{
    private View self_view;

    private RecyclerView mZhandou;
    private JSONArray jsob;
    private RelativeLayout RelativeLayout01,RelativeLayout02,RelativeLayout03;
    private Button fdzhBtn,dzbBtn,bzdBtn,dzbQR,bzdQR;
    private ImageButton fdzhFh,dzbFh,bzdFh;
    private EditText dzbNumber,bzdnumber;
    private TextView dzbfbnumber,dzbdqnumber,bzdfbnumber,bzddqnumber,fdnumber,fbnumber;
    int bzdnumber1,cznumber=0,zsnumber=0,fbnumber1=0;

    public static Tabbar02 newInstance(String param){
        Tabbar02 tabbar02 = new Tabbar02();
        Bundle args = new Bundle();
        args.putString("agrs2",param);
        tabbar02.setArguments(args);
        return tabbar02;
    }

    public Tabbar02(){

    }

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState){

        if(self_view != null){
            init();
            return self_view;
        }
        View view = inflater.inflate(R.layout.tabbar02,container,false);
        self_view = view;
        init();

        final RefreshLayout refreshLayout1 = view.findViewById(R.id.zhandouLayout);
        refreshLayout1.setOnRefreshListener(new OnRefreshListener() {
            public void onRefresh(RefreshLayout refreshlayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if(jsob==null) {
                            Toast.makeText(getActivity(), "已经没有更多数据了", Toast.LENGTH_SHORT).show();
                            refreshLayout1.finishRefresh();
                        }else{
                            Toast.makeText(getActivity(), "查询成功", Toast.LENGTH_SHORT).show();
                            refreshLayout1.finishRefresh();
                        }
                        /**
                         * 刷新完成后调用此方法，要不然刷新效果不消失
                         */

                    }
                }, 0);
            }
        });
        refreshLayout1.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
//        chaxun();
       // showToast(getActivity(),jsob+"");

        RelativeLayout01 = self_view.findViewById(R.id.fdzhid);
        RelativeLayout02 = self_view.findViewById(R.id.dzbid);
        RelativeLayout03 = self_view.findViewById(R.id.bzdid);
        fdzhBtn = self_view.findViewById(R.id.fdzhBtn);
        dzbBtn = self_view.findViewById(R.id.fdzfbbtn_01);
        bzdBtn = self_view.findViewById(R.id.fbzfbbtn_01);
        fdzhFh = self_view.findViewById(R.id.fdzhfh);
        dzbFh = self_view.findViewById(R.id.dzbfh);
        bzdFh = self_view.findViewById(R.id.bzdfh);
        dzbNumber = self_view.findViewById(R.id.dzbnumber);
        dzbfbnumber = self_view.findViewById(R.id.dzbfbnumber);
        bzdnumber = self_view.findViewById(R.id.bzdnumber);
        dzbQR = self_view.findViewById(R.id.dzbqr);
        bzdQR = self_view.findViewById(R.id.bzdqr);
        dzbdqnumber = self_view.findViewById(R.id.dzbdqnumber);
        bzddqnumber = self_view.findViewById(R.id.bzddqnumber);
        bzdfbnumber = self_view.findViewById(R.id.bzdfbnumber);
        fdnumber = self_view.findViewById(R.id.fdnumber);
        fbnumber = self_view.findViewById(R.id.fbnumber);
        final InputMethodManager imm = (InputMethodManager) getActivity()
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        //点击右上角按钮时显示第一个页面
        fdzhBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OKManager.getInstance().type1006("339", new OKManager.func4() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            JSONObject jsob = (JSONObject) jsonObject.get("data");
                            cznumber = Integer.parseInt(jsob.get("free_credits").toString());
                            zsnumber = Integer.parseInt(jsob.get("paycheck_credits").toString());
                            fbnumber1 = Integer.parseInt(jsob.get("gamecoin").toString());
                            fbnumber.setText(fbnumber1+"");
                            bzddqnumber.setText(fbnumber1+"");
                            int number = cznumber + zsnumber;
                            fdnumber.setText(number+"");
                            dzbdqnumber.setText(number+"");
                            imm.hideSoftInputFromWindow(dzbNumber.getWindowToken(), 0);

                            RelativeLayout01.setVisibility(self_view.VISIBLE);
                            RelativeLayout03.setVisibility(self_view.GONE);
                            RelativeLayout02.setVisibility(self_view.GONE);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                    @Override
                    public void onFailure(String string) {

                    }
                });
            }
        });
        //点击疯豆转疯币隐藏第一个页面显示第二个页面
        dzbBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RelativeLayout01.setVisibility(self_view.GONE);
                RelativeLayout02.setVisibility(self_view.VISIBLE);
            }
        });
        //点击疯币转疯豆隐藏第一个页面显示第三个页面
        bzdBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RelativeLayout01.setVisibility(self_view.GONE);
                RelativeLayout03.setVisibility(self_view.VISIBLE);
            }
        });
        //返回按钮隐藏当前窗口并收起键盘
        fdzhFh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RelativeLayout01.setVisibility(self_view.GONE);
                imm.hideSoftInputFromWindow(dzbNumber.getWindowToken(), 0);
            }
        });
        //返回按钮隐藏当前窗口并收起键盘
        dzbFh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RelativeLayout02.setVisibility(self_view.GONE);
                imm.hideSoftInputFromWindow(dzbNumber.getWindowToken(), 0);
            }
        });
        //返回按钮隐藏当前窗口并收起键盘
        bzdFh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RelativeLayout03.setVisibility(self_view.GONE);
                imm.hideSoftInputFromWindow(dzbNumber.getWindowToken(), 0);
            }
        });
        //捕捉键盘输入事件
        TextWatcher textWatcher1 = new TextWatcher() {
            // 输入文本之前的状态
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            // 输入文本中的状态
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String number = charSequence.toString();
                int number1 = 0;
                if(!number.equals("")) {
                    number1 = Integer.parseInt(number);
                }else{
                    dzbfbnumber.setText("0");
                }
                if(!number.equals("")&&number1>0) {
                    dzbfbnumber.setText(number + "00");
                }
            }
            // 输入文本之后的状态
            @Override
            public void afterTextChanged(Editable editable) {
            }
        };
        //捕捉键盘输入事件
        TextWatcher textWatcher2 = new TextWatcher() {
            // 输入文本之前的状态
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }
            // 输入文本中的状态
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String number = charSequence.toString();
                int number1 = 0;
                if(!number.equals("")) {
                    number1 = Integer.parseInt(number);
                }else{
                    bzdfbnumber.setText("0");
                }
                if(!number.equals("")&&number1>=100) {
                    bzdfbnumber.setText(number1/100+"");
                }
            }
            // 输入文本之后的状态
            @Override
            public void afterTextChanged(Editable editable) {
            }
        };
        //只允许输入数字
        dzbNumber.setInputType(InputType.TYPE_CLASS_NUMBER);
        bzdnumber.setInputType(InputType.TYPE_CLASS_NUMBER);
        //添加键盘输入事件
        dzbNumber.addTextChangedListener(textWatcher1);
        bzdnumber.addTextChangedListener(textWatcher2);
        //豆转币确认
        dzbQR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String number2 = dzbdqnumber.getText().toString();
                String srnumber = dzbNumber.getText().toString();
                if(srnumber.trim().equals("")){
                    showToast(getActivity(),"请输入需要转换的数量");
                }else if(srnumber.equals("0")){
                    showToast(getActivity(),"数量不能等于0!");
                }else if(Integer.parseInt(srnumber)>Integer.parseInt(number2)){
                    showToast(getActivity(),"疯豆数量不足!");
                }else{
                    OKManager.getInstance().type1007("339", srnumber, new OKManager.func4() {
                        @Override
                        public void onResponse(JSONObject jsonObject) {
                            try {
                                if(jsonObject.get("code").toString().trim().equals("0")) {
                                    showToast(getActivity(),jsonObject.get("message")+"");
                                    RelativeLayout02.setVisibility(self_view.GONE);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(String string) {

                        }
                    });
                }
            }
        });
        bzdQR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String number2  = bzddqnumber.getText().toString();
                String srnumber = bzdnumber.getText().toString();
                if(srnumber.trim().equals("")){
                    showToast(getActivity(),"请输入需要转换的数量");
                }else if(srnumber.equals("0")){
                    showToast(getActivity(),"数量不能等于0!");
                }else if(Integer.parseInt(srnumber)%100!=0){
                    showToast(getActivity(),"请输入100的倍数!");
                }else if(Integer.parseInt(srnumber)>Integer.parseInt(number2)){
                    showToast(getActivity(),"疯比数量不足!");
                }else{

                    OKManager.getInstance().type1008("339", srnumber, new OKManager.func4() {
                        @Override
                        public void onResponse(JSONObject jsonObject) {
                            try {
                                if(jsonObject.get("code").toString().trim().equals("0")) {
                                    showToast(getActivity(),jsonObject.get("message")+"");
                                    RelativeLayout03.setVisibility(self_view.GONE);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(String string) {

                        }
                    });
                }
            }
        });
        return view;
    }
    public static void showToast(final Activity ctx, final String msg) {
        // 判断是在子线程，还是主线程
        if ("main".equals(Thread.currentThread().getName())) {
            Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
        } else {
            // 子线程
            ctx.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

  public void  init(){
      OKManager.getInstance().type1005(new OKManager.func4() {
          @Override
          public void onResponse(JSONObject jsonObject) {
              try {
                  jsob = (JSONArray) jsonObject.get("data");
                  mZhandou = self_view.findViewById(R.id.zhandoutab);
                  mZhandou.setLayoutManager(new LinearLayoutManager(getActivity()));
                  mZhandou.setAdapter(new ZDAdapter(getActivity(),jsob));


                  //Log.e("++++++++",jsob.length()+"");
              } catch (JSONException e) {
                  e.printStackTrace();
              }
          }

          @Override
          public void onFailure(String string) {
              showToast(getActivity(),string);
          }
      });
  }
//public void tiaozhuan(String game_id,String user_id){
//    Intent intent = new Intent(getActivity(),GameActivity.class);
//    intent.putExtra("ganme_id",game_id);
//    intent.putExtra("user_id",user_id);
//    startActivity(intent);
//}
}
